//
// signalr.js
// hs-admin
//
// Created by 区区电脑 on 2023/05/01.
//

import * as Signalr from "@microsoft/signalr";
import LocalDB from "@/utils/LocalDB.js"
import {jsonInitialToLowercase, jsonInitialToUpcase} from "@/utils/utils.js"



let signalrConnection;

const $signalr = {
    // 链接
    connection: async () => {
        const headers = {};
        const token = LocalDB.getItem("token");
        const xToken = LocalDB.getItem("x_token");
        if (token.data) {
            console.log("有token");
            headers["Authorization"] = token.data;
        }
        if (xToken.data) {
            headers["X-Authorization"] = xToken.data;
        }
        signalrConnection = new Signalr.HubConnectionBuilder()
            .withUrl(`${window.$config.baseUrl}/Hubs/MessageHub`, {headers, accessTokenFactory: () => (token.data||"").replace("Bearer ", "")})
            //.configureLogging(Signalr.LogLevel.Information)
            .build();
        try {
            await signalrConnection.start();
            console.log("SignalR Connected.");
        } catch (err) {
            console.log(err);
            setTimeout($signalr.connection, 5000);
        }
        console.primary("链接 $signalr")
        signalrConnection.onclose($signalr.onclose)
    },
    stop: () => {
        signalrConnection.stop();
    },
    onclose: (async () => {
        console.danger("$signalr 意外关闭", "正在尝试重连...")
        await $signalr.connection();
    }),
    // 向服务端发送消息
    send: async (methodName, data) => {
        try {
            data = jsonInitialToUpcase(data)
            data = JSON.stringify(data)
        } catch (e) {
            console.warning("signalr send json error", data)
        }
        try {
            await signalrConnection.invoke(methodName, data);
        } catch (e) {
            console.danger("signalr 调用服务端错误", methodName, e)
        }
    },
    // 接收服务端发送的消息
    on: (methodName, callback) => {
        signalrConnection.on(methodName, (data) => {
            try {
                data = JSON.parse(data)
                data = jsonInitialToLowercase(data)
            } catch (e) {
                console.warning("signalr on json error", data)
            }
            callback && callback(data)
        })
    },
    /**
     * 关闭事件监听
     * @param methodName
     */
    off: (methodName) => {
        signalrConnection.off(methodName)
    }
}

export default $signalr;
